package com.jdrx.sw.sewage.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.jdrx.platform.commons.rest.beans.vo.ResponseVO;
import com.jdrx.platform.commons.rest.factory.ResponseFactory2;
import com.jdrx.sw.sewage.beans.dto.DevStorageDTO;
import com.jdrx.sw.sewage.beans.entity.*;
import com.jdrx.sw.sewage.beans.vo.DevStorageTypeVO;
import com.jdrx.sw.sewage.beans.vo.ExcelBaImGreDevVO;
import com.jdrx.sw.sewage.common.converter.LocalDateConverter;
import com.jdrx.sw.sewage.common.util.SpringBeanUtil;
import com.jdrx.sw.sewage.common.util.StringUtil;
import com.jdrx.sw.sewage.dao.*;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

import static com.jdrx.sw.sewage.common.constant.Constant.*;

@Service
public class GDDataImportServiceImpl extends AnalysisEventListener<ExcelBaImGreDevVO> {

    public static final Logger logger = LoggerFactory.getLogger(GDDataImportServiceImpl.class);

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private DictServiceImpl dictServiceImpl;
    @Autowired
    private ProcessunitDAO processunitDAO;
    @Autowired
    private GatherDevDAO gatherDevDAO;
    @Autowired
    private GatherDevPointDAO gatherDevPointDAO;
    @Autowired
    private DevStorageTypeDAO devStorageTypeDAO;
    @Autowired
    private DevStorageDAO devStorageDAO;
    @Autowired
    private DeviceDAO deviceDAO;
    @Autowired
    private MaterielDAO materielDAO;

    /**
     * 这个每一条数据解析都会来调用
     */
    @SneakyThrows
    @Override
    public void invoke(ExcelBaImGreDevVO data, AnalysisContext context) {
        logger.info("解析到一条数据:{}", JSON.toJSONString(data));
        //校验工艺单元
        Map<String, Object> params = Maps.newHashMap();

        String processunit = StringUtil.removeStrMatcher(data.getProcessunit());
        String gatherDev = data.getGatherDev();
        String gatherDevPoint = data.getGatherDevPoint();
        if (gatherDev.contains(NH3NY)) gatherDev = NH3NY;
        if (gatherDev.contains(BOD5Y)) gatherDev = BOD5Y;
        if (gatherDev.contains(H2SY)) gatherDev = H2SY;
        if (gatherDevPoint.contains(H2S)) gatherDevPoint = H2S;
        if (gatherDevPoint.contains(NH3N)) gatherDevPoint = NH3N;
        if (gatherDevPoint.contains(BOD5)) gatherDevPoint = BOD5;

        if (!gatherDev.contains(NH3NY) && !gatherDev.contains(BOD5Y) && !gatherDev.contains(H2SY))
            gatherDev = StringUtil.removeStrMatcher(gatherDev);
        if (!gatherDevPoint.contains(NH3N) && !gatherDevPoint.contains(BOD5) && !gatherDevPoint.contains(H2S))
            gatherDevPoint = StringUtil.removeStrMatcher(gatherDevPoint);

        Long stationId = Long.valueOf(request.getHeader(TRANSPARENT_STATIONID_FEILD));
        Integer plcLogicPoint = data.getPlcLogicPoint();

        DictPO dictPO = null;
        Integer strMatcher = null;
        ProcessunitPO processunitPO = processunitDAO.selectBySIdAndV(stationId, data.getProcessunit(), data.getFactoryPeriod());
        if (Objects.isNull(processunitPO)) {
            params.put(CLASSIFYKEY, PROCESSUNITCLASSIFY);
            params.put(VALUE, processunit);
            dictPO = dictServiceImpl.getByParams(params, null);

            processunitPO = new ProcessunitPO();
            strMatcher = StringUtil.getStrMatcher(data.getProcessunit());
            if (0 == strMatcher) processunitPO.setName(dictPO.getDisName());
            else processunitPO.setName(dictPO.getDisName() + strMatcher);
            processunitPO.setStationId(stationId);
            processunitPO.setDictId(dictPO.getId());
            processunitPO.setValue(data.getProcessunit());
            processunitPO.setFactoryPeriod(data.getFactoryPeriod());
            processunitDAO.insert(processunitPO);
        }

        GatherDevPO gatherDevPO2 = gatherDevDAO.selectBusIdAndva(stationId, data.getGatherDev(), data.getProcessunit());
        GatherDevPO gatherDevPO = new GatherDevPO();
        if (Objects.nonNull(gatherDevPO2)) BeanUtils.copyProperties(gatherDevPO2, gatherDevPO);
        if (Objects.isNull(gatherDevPO2)) {
            //校验设备
            params.put(CLASSIFYKEY, GATRDEVCLASSIFY);
            params.put(VALUE, gatherDev);
            dictPO = dictServiceImpl.getByParams(params, null);

            gatherDevPO = new GatherDevPO();
            gatherDevPO.setProcessunitId(processunitPO.getId());
            gatherDevPO.setValue(data.getGatherDev());
            strMatcher = StringUtil.getStrMatcher(data.getGatherDev());
            if (0 == strMatcher || data.getGatherDev().contains(NH3N)) gatherDevPO.setDeviceName(dictPO.getDisName());
            else gatherDevPO.setDeviceName(data.getGatherDevName());

//            if (null != PROC_SHOW_DEVICE.get(gatherDev)) gatherDevPO.setProcShow(1);
//            else gatherDevPO.setProcShow(0);
            gatherDevPO.setProcShow(0);
            gatherDevPO.setDictId(dictPO.getId());
            gatherDevPO.setStationId(stationId);
            gatherDevPO.setFactoryPeriod(data.getFactoryPeriod());
            gatherDevPO.setPlcLogicPoint(plcLogicPoint);
            gatherDevDAO.insert(gatherDevPO);
        }

        String gatherDevPointStr = data.getProcessunit() + "_" + data.getGatherDev() + "_";
        String d_change = D_CHANGE.get(data.getGatherDevPoint());
        if (StringUtils.isEmpty(d_change))
            gatherDevPointStr = gatherDevPointStr + data.getGatherDevPoint() + "_" + data.getGatherDevPointFeat();
        else {
            gatherDevPoint = d_change;
            gatherDevPointStr = gatherDevPointStr + gatherDevPoint + "_" + data.getGatherDevPointFeat();
        }

        GatherDevPointPO gatherDevPointPO = gatherDevPointDAO.selectBusIdAndva(stationId, gatherDevPointStr);
        if (Objects.isNull(gatherDevPointPO)) {
            //校验点位
            params.put(CLASSIFYKEY, GATRDEVPOINTCLASSIFY);
            params.put(VALUE, gatherDevPoint);
            dictPO = dictServiceImpl.getByParams(params, null);

            gatherDevPointPO = new GatherDevPointPO();
            gatherDevPointPO.setName(dictPO.getDisName());
            gatherDevPointPO.setPdgName(data.getGatherName());
            gatherDevPointPO.setValue(gatherDevPointStr);
            gatherDevPointPO.setGValue(dictPO.getValue());
            gatherDevPointPO.setGatherDevId(gatherDevPO.getId());
            gatherDevPointPO.setDictId(dictPO.getId());
            gatherDevPointPO.setStationId(stationId);
            gatherDevPointPO.setIotGatewayNum(data.getGatewayNum());
            gatherDevPointPO.setParUnit(data.getUnit());
            gatherDevPointPO.setParValue(data.getParValue());
            gatherDevPointPO.setReadWrite(data.getReadWrite() == 1 ? true : false);
            gatherDevPointPO.setPrecision(data.getPrecision());
            gatherDevPointPO.setControlType(data.getGatherDevPointFeat());
            gatherDevPointPO.setFactoryPeriod(data.getFactoryPeriod());
            gatherDevPointPO.setPlcLogicPoint(plcLogicPoint);
            gatherDevPointPO.setPValue(data.getProcessunit());
            gatherDevPointDAO.insert(gatherDevPointPO);
        }/*else {
            params.put(CLASSIFYKEY, GATRDEVPOINTCLASSIFY);
            params.put(VALUE, gatherDevPoint);
            dictPO = dictServiceImpl.getByParams(params, null);

            gatherDevPointPO.setName(dictPO.getDisName());
            gatherDevPointPO.setPdgName(data.getGatherName());
            gatherDevPointPO.setValue(gatherDevPointStr);
            gatherDevPointPO.setGValue(dictPO.getValue());
            gatherDevPointDAO.update(gatherDevPointPO);
        }*/

        //自动入库 + 自动领用
        DevStorageTypeVO devStorageTypeVO = devStorageTypeDAO.findByPlcLogicPoint(1);
        if (Objects.isNull(devStorageTypeVO)) {
            DevStorageDTO devStorageDTO = new DevStorageDTO();
            devStorageDTO.setPlcLogicPoint(1);
            devStorageTypeDAO.add(devStorageDTO);
            devStorageTypeVO = new DevStorageTypeVO();
            devStorageTypeVO.setId(devStorageTypeDAO.selectNextId() - 1);
        }

        if (Objects.isNull(gatherDevPO2) && plcLogicPoint == 1) {
            DevStoragePO devStoragePO = new DevStoragePO();
            devStoragePO.setPlcLogicPoint(1);
            devStoragePO.setInitWorkTime(0);
            devStoragePO.setStorageTypeId(devStorageTypeVO.getId());
            if ("Y".equals(data.getGatherDevPointFeat()))
                devStoragePO.setMaterielId(materielDAO.selectByName(YB).getId());
            else devStoragePO.setMaterielId(materielDAO.selectByName(SB).getId());
            devStorageDAO.add(devStoragePO);
            devStoragePO.setId(devStorageDAO.selectNextId());

            DevicePO devicePO = new DevicePO();
            devicePO.setStationId(stationId);
            devicePO.setDevStorageId(devStoragePO.getId());
            devicePO.setNoDispatch(0);
            devicePO.setGatherDevId(gatherDevPO.getId());
            devicePO.setProcessunitId(processunitPO.getId());
            devicePO.setCollectPoint(1);
            deviceDAO.assetsCollect(devicePO);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        logger.info("所有数据导入完成！");
    }

    public ResponseVO collectionDataImport(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), ExcelBaImGreDevVO.class, SpringBeanUtil.getBean(GDDataImportServiceImpl.class))
                .registerConverter(new LocalDateConverter())
                .sheet()
                .doRead();
        return ResponseFactory2.ok("导入成功");
    }
}